package de.dopichaj.labrador.tools;


import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Collections;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.text.TextAction;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.lang.Validate;
import org.apache.xml.resolver.tools.CatalogResolver;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import de.dopichaj.labrador.index.IndexVersionException;
import de.dopichaj.labrador.index.lucene.LuceneFileSystemIndex;

/**
 * Explore patterns with a Swing GUI.
 */
public final class PatternExplorer extends JFrame {

    private static final long serialVersionUID = 1L;
    private final PatternTableModel resultTableModel;
    private final JLabel infoBar;
    private final PatternFinder finder;
    private final JTextArea fragment;
    private final JScrollPane fragmentScroll;
    private final JTable resultTable;
    

    public PatternExplorer() throws HeadlessException, IOException, IndexVersionException {
        super("PatternExplorer");

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        
        final Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());

        fragment = new JTextArea(0, 0);
        fragment.setEditable(false);
        fragment.setLineWrap(true);
        fragment.setWrapStyleWord(true);
        fragmentScroll = new JScrollPane(fragment);
        fragmentScroll.setPreferredSize(new Dimension(400, 0));

        finder = new PatternFinder(
            new LuceneFileSystemIndex(new File("linux-howtos/de.dopichaj.labrador.index")));
        infoBar = new JLabel("Start searching!");
        resultTableModel = new PatternTableModel();
        resultTable = new JTable(resultTableModel);
        resultTable.getColumnModel().setColumnSelectionAllowed(false);
        resultTable.setRowSelectionAllowed(true);
        resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        resultTable.getSelectionModel().
            addListSelectionListener(new ResultTableSelection());
        
        final Container searchContainer = createSearchField(infoBar, resultTableModel);
        
        contentPane.add(searchContainer, BorderLayout.NORTH);
        contentPane.add(
            new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(resultTable), fragmentScroll),
            BorderLayout.CENTER);
        
        setSize(1000, 500);
        setVisible(true);
    }
    
    public void searchFor(String pattern) {
        infoBar.setText("Searching for " + pattern + " ...");
        new SearchThread(this, finder, pattern).start();
     }
    
    public void setSearchResults(List<ContextInformation> contexts) {
        infoBar.setText(contexts.size() + " results.");
        resultTableModel.setContexts(contexts);
        if (contexts.size() > 0) {
            final ContextInformation context = contexts.get(0);
            displayFragment(context);
        } else {
            fragment.setText("");
        }
    }

    private void displayFragment(final ContextInformation context) {
        fragment.setText(getFragment(context.getFile(), context.getXPath()));
        fragment.setCaretPosition(0);
    }

    public String getFragment(File file, String xPathExpression) {
        
        Validate.notNull(file);
        Validate.notNull(xPathExpression);
        
        try {
            final Transformer transformer =
                TransformerFactory.newInstance().newTransformer();
            final XPath xPath = XPathFactory.newInstance().newXPath();

            DocumentBuilder builder =
                DocumentBuilderFactory.newInstance().newDocumentBuilder();
            builder.setEntityResolver(new CatalogResolver());
            
            Document doc = builder.parse(file);
            
            Node fragment = (Node)xPath.evaluate(xPathExpression, doc,
                XPathConstants.NODE);
            StringWriter result = new StringWriter();
            transformer.transform(
                new DOMSource(fragment), new StreamResult(result));
            return result.toString();
        } catch (Exception e) {
            if (e instanceof RuntimeException) {
                throw (RuntimeException)e;
            }
        }
        return "[could not get fragment]";
    }

    private static final class SearchThread extends Thread {

        private final PatternExplorer explorer;
        private final String pattern;
        private final PatternFinder finder;
         
        public SearchThread(PatternExplorer explorer, PatternFinder finder,
            String pattern) {
            
            this.explorer = explorer;
            this.finder = finder;
            this.pattern = pattern;
        }
        
        @Override
        public void run() {
            final List<ContextInformation> results =
                finder.getContextsMatching(pattern);
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    explorer.setSearchResults(results);
                }
            });
        }
    }

    private Container createSearchField(final JLabel infoBar, final PatternTableModel model) {
        final JTextField searchSignature = new JTextField(50);
        searchSignature.setText("[2-9]e0...*");
        searchSignature.getKeymap().addActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
            new SearchFieldListener(searchSignature, this));
        final Container searchContainer = new JPanel();
        searchContainer.setLayout(new BorderLayout());
        searchContainer.add(searchSignature, BorderLayout.NORTH);
        searchContainer.add(infoBar, BorderLayout.SOUTH);
        return searchContainer;
    }
    
    private final class ResultTableSelection
        implements ListSelectionListener {

        public void valueChanged(ListSelectionEvent e) {
            final int selected = resultTable.getSelectedRow();
            if (!e.getValueIsAdjusting() && selected != -1) {
                
                displayFragment(resultTableModel.getContexts().get(selected));
            }
        }
    }
    
    private static final class SearchFieldListener extends TextAction {
        private static final long serialVersionUID = 1L;
        final PatternExplorer explorer;
        final JTextField text;

        public SearchFieldListener(JTextField text, PatternExplorer explorer) {
            super("Enter");
            this.explorer = explorer;
            this.text = text;
        }

        public void actionPerformed(ActionEvent e) {
            explorer.searchFor(text.getText());
        }

    }
    
    private static final class PatternTableModel extends AbstractTableModel {

        private static final long serialVersionUID = 1L;
        private static final String[] columns = new String[] {
            "signature", "XPath"
        };
        private static final Class<?>[] columnClasses = new Class<?>[] {
            String.class, String.class
        };

        private List<ContextInformation> contexts = Collections.emptyList();
        
        public int getRowCount() {
            return contexts.size();
        }

        public int getColumnCount() {
            return columns.length;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            ContextInformation context = contexts.get(rowIndex);
            switch (columnIndex) {
            case 0:
                return context.getSignature();
            case 1:
                return context.getCompactXPath();
            default:
                return null;
            }
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return columnClasses[columnIndex];
        }

        @Override
        public String getColumnName(int column) {
            return columns[column];
        }

        public List<ContextInformation> getContexts() {
            return contexts;
        }

        public void setContexts(List<ContextInformation> contexts) {
            this.contexts = contexts;
            fireTableDataChanged();
        }
    }
    
    public static void main(String[] args) throws Exception {
        new PatternExplorer();
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/